var urlparse = require('url').parse;
var Weibo = require('nodeweibo');    // require('nodeweibo') also works if you have installed nodeweibo via npm
var setting = require('./setting.json');   // get setting (appKey, appSecret, etc.)
var User = require('./js/user');
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var shell = require('./js/shell');
var i18n = require('./js/i18n');
var ui = require('./js/ui');
var FACE_TYPES = require('./js/lib/emotional').faces;

function sendRepost(msg, id, direct) {
    var $btn = $("#replySubmit");
    var $txt = $("#replyTextarea");
    var sid = sid || $('#repostTweetId').val() || id;
    var user = User.getUser();
    var is_comment = 0;
    // var config = tapi.get_config(user);
    $btn.attr('disabled','true');
    $txt.attr('disabled','true');

    if(!direct){
        var $chk_sendOneMore = $('#chk_sendOneMore');
        if ($chk_sendOneMore.attr("checked") && $chk_sendOneMore.val()) { // 同时给XXX评论
            is_comment = 1;/*评论给当前微博*/
        }
        var $chk_sendOneMore2 = $('#chk_sendOneMore2');
        if ($chk_sendOneMore2.attr("checked") && $chk_sendOneMore2.val()) { // 同时给原作者 XXX评论
            if(is_comment){
                is_comment = 3;/*都评论*/
            }else{
                is_comment = 2;/*评论给原微博*/
            }
        }
    }

    var loading = $('#loading').show();
    /*发送转发的消息*/
    var para = {
        "source"        :   Weibo.appKey.appKey,
        "access_token"  :   user.access_token,
        "id"            :   sid,
        "status"        :   msg,
        "is_comment"    :   is_comment
    };

    Weibo.Statuses.repost(para, function(err, data){
        console.log(data);
        loading.hide();
        $btn.removeAttr('disabled');
        $txt.removeAttr('disabled');
        if (err) {
            return ui.showErrorTips(err);
        }
        $('.close_dialog:first').click();
        ui.showTips(i18n.get("msg_repost_success"));
    });

}

function sendComment(msg) {
    var btn = $("#replySubmit");
    var txt = $("#replyTextarea");
    var cid = $('#commentCommentId').val();
    var sid = $('#commentTweetId').val();
    var user = User.getUser();
    var is_repost = 0;/*评论的同时是否转发*/
    var comment_ori = 0;/*当评论转发微博时，是否评论给原微博，0：否、1：是，默认为0*/
    btn.attr('disabled', true);
    txt.attr('disabled', true);

    var $chk_sendOneMore = $('#chk_sendOneMore');
    if ($chk_sendOneMore.attr("checked") && $chk_sendOneMore.val()) {
        is_repost = 1;/*同时转发一条微博*/
    }
    var $chk_sendOneMore2 = $('#chk_sendOneMore2');
    if ($chk_sendOneMore2.attr("checked") && $chk_sendOneMore2.val()) { // 同时给原作者 XXX评论
        comment_ori = 1;
    }
    if(cid){/*执行回复评论*/
        var para = {
            "source"        :   Weibo.appKey.appKey,
            "access_token"  :   user.access_token,
            "id"            :   sid,
            "cid"           :   cid,
            "comment"       :   msg,
            "comment_ori"    :   comment_ori
        };
        var loading = $('#loading').show();
        Weibo.Comments.reply(para, function(err, data){
            loading.hide();
            txt.removeAttr('disabled');
            btn.removeAttr('disabled');
            if (err) {
                return ui.showErrorTips(err);
            }
            $('.close_dialog:first').click();
            txt.val('');
            ui.showTips(i18n.get("msg_comment_success"));
        });
    }else{/*直接评论*/
        var para = {
            "source"        :   Weibo.appKey.appKey,
            "access_token"  :   user.access_token,
            "id"            :   sid,
            "comment"       :   msg,
            "comment_ori"   :   comment_ori
        };
        var loading = $('#loading').show();
        Weibo.Comments.create(para, function(err, data){
            loading.hide();
            txt.removeAttr('disabled');
            btn.removeAttr('disabled');
            if (err) {
                return ui.showErrorTips(err);
            }
            $('.close_dialog:first').click();
            txt.val('');
            ui.showTips(i18n.get("msg_comment_success"));
        });

    }
    if(is_repost){/*同时转发评论*/
        sendRepost(msg, sid, 1);
    }
}

function sendMsgByActionType(c) {
    if (!c) {
        return ui.showTips(i18n.get("msg_need_content"));
    }

    $("#replySubmit, #replyTextarea").attr('disabled', true);

    __sendMsgByActionType(c);
}

function __sendMsgByActionType(c) {
    var actionType = $('#actionType').val();
    switch (actionType) {
        case 'repost': // 转
            sendRepost(c);
            break;
        case 'comment': // 评
            sendComment(c);
            break;
        case 'reply': // @
            sendReplyMsg(c);
            break;
        default:
            ui.showTips('Wrong Send Type');
            $("#replySubmit, #replyTextarea").attr('disabled', false);
            break;
    }
}

var stateManager = new EventEmitter();

function Controller() {
    this.init();
}

Controller.prototype.init = function () {
    for (var i = 0; i < this.events.length; i++) {
        var item = this.events[i];
        this.bindEvents(item.events, item.selecter, item.handler);
    }
};

Controller.prototype.bindEvents = function (events, selecter, handler) {
    $(document).on(events, selecter, {controller: this}, handler);
};

function StatusController() {
    this.events = [
        //{ events: 'mousedown', selecter: '.thumbnail_pic', handler: this.viewOriginalImage },
        { events: 'click', selecter: '.thumbnail_pic', handler: this.viewOriginalImage },
    ];
    StatusController.super_.call(this);
}
inherits(StatusController, Controller);

StatusController.prototype.viewOriginalImage = function (event) {
    var self = event.data.controller;
    var img = $(this);
    var originalURL = img.attr('original').trim();
    if (!originalURL) {
        return;
    }
    console.log('md ' + event.which);
    //if (event.which === 3) {
        openNewWindow(originalURL);
        //return false;
   // }
};

StatusController.prototype.previewImage = function (event) {
    var self = event.data.controller;
    var img = $(this);
    var originalURL = img.attr('original').trim();
    if (!originalURL) {
        return;
    }
    if (img.find('.img_loading').length === 0) {
        img.append('<img class="img_loading" src="images/loading.gif" />');
    } else {
        img.find('.img_loading').show();
    }
    ui.popupBox.showImg(img.attr('bmiddle'), originalURL, function () {
        img.find('.img_loading').hide();
    });
    return false;
};

/*控制主页面显示，微薄内容，@，收藏，评论，随便看看的控制器*/
function MainController() {

    this.lastTimelines = {}; // cache user last timeline type

    this.events = [
        /*置顶按钮*/
        { events: 'click', selecter: '#gototop',        handler: this.gotop },/*发送按钮*/
        /*首页，收藏，@，以及随便看看的click事件*/
        { events: 'click', selecter: '.timeline_tab',   handler: this.show },/*首页，@我，@我的评论，评论，私信，收藏，我的微博，点击按钮事件*/
        /*点赞，收藏，取消收藏，转发，评论，click点击事件*/
        { events: 'click', selecter: '.reposttweet',    handler: this.showRepostDialog },/*转发*/
        { events: 'click', selecter: '.commenttweet',   handler: this.showCommentDialog },/*评论*/
        /*转发，评论的dialog 上面的点击事件*/
        { events: 'click', selecter: '.close_dialog',   handler: this.hideDialog },/*x按钮,关闭按钮*/
        { events: 'click', selecter: '#replySubmit',    handler: this.sendReply },/*发送按钮*/

        /*转发详细信息，和评论详细信息下拉列表显示*/
        { events: 'click', selecter: '.commentCounts a, .repostCounts a',   handler: this.DetailShow },
        { events: 'click', selecter: '.comment_hide_list_btn',              handler: this.DetailHide },
        { events: 'click', selecter: '.comments .pre_page',                 handler: this.DetailPrevPage },
        { events: 'click', selecter: '.comments .next_page',                handler: this.DetailNextPage }

    ];

    $(".list_warp").on('scrollstop', { controller: this }, this.checkScroll);



    /*dialog 输入框部分*/
    this.$replyText = $('#replyTextarea');

    this.$replyText.on('input focus', { controller: this }, this.dialogcount);

    MainController.super_.call(this);

}

inherits(MainController, Controller);

MainController.prototype.DetailHide = function (event) {
    var btn = $(this);
    btn.closest('.comments').hide();
};

MainController.prototype.DetailShow = function (event) {
    var btn = $(this);
    var self = event.data.controller;
    var wrap = btn.closest('.commentWrap').find('.comments');
    wrap.hide();
    var toType = btn.data('type') || 'comment';
    wrap.data('type', toType);
    self.showPage(wrap, 'first');
}

MainController.prototype.DetailPrevPage = function (event) {
    var btn = $(this);
    var self = event.data.controller;
    var wrap = btn.parents('.comments');
    self.showPage(wrap, 'prev');
};

MainController.prototype.DetailNextPage = function (event) {
    var btn = $(this);
    var self = event.data.controller;
    var wrap = btn.parents('.comments');
    self.showPage(wrap, 'next');
};

MainController.prototype.showPage = function (wrap, action) {
    var type = wrap.data('type') || 'comment';
    var sid = wrap.data('id');
    var user = User.getUser();
    var list = wrap.find('.comment_list');
    var params = {
        "source"        : Weibo.appKey.appKey,
        "access_token"  : user.access_token,
        "count"         : 8,
        "id"            : sid
    };
    if (action === 'next') {
        var max_id = wrap.data('max_id');
        var max_time = wrap.data('max_time');
        if (max_id) {
            params.max_id = max_id;
            if (max_time) {
                params.max_time = max_time;
            }
        }
    } else if (action === 'prev') {
        var since_id = wrap.data('since_id');
        var since_time = wrap.data('since_time');
        if (since_id) {
            params.since_id = since_id;
            if (since_time) {
                params.since_time = since_time;
            }
        }
    }
    // console.log(sid + ' params: ' + JSON.stringify(params));
    var loading = $('#loading').show();
    var method = type === 'repost' ? 'repost_timeline' : 'comments';
    if(type === 'repost')/*显示转发详细列表,目前可能由于api本身的问题不能获取到转发信息*/{
        Weibo.Statuses.repost_timeline(params, function(err, data){
            loading.hide();
            if (err) {
                return ui.showErrorTips(err);
            }
            var nextBtn = wrap.find('.next_page');
            var preBtn = wrap.find('.pre_page');
            if(data.length === 0){
                return ui.showTips('没有了');
            }
            var items = data.reposts;
            if (items.length === 0) {
                if (action === 'next') {
                    nextBtn.hide();
                } else if (action === 'prev') {
                    preBtn.hide();
                }
                return ui.showTips('没有了');
            }
            var html = '';
            var buildMethod = type === 'repost' ? 'buildRepost' : 'buildComment';
            for (var i = 0; i < items.length; i++) {
                html += ui[buildMethod](user, items[i]);
            }
            list.html(html);
            // set comment_#id data
            ViewCache.setCommentItems(items);
            if (buildMethod === 'buildRepost') {
                // cache them for repost
                ViewCache.setItems(items);
            }
            nextBtn.show();
            preBtn.show();
            if (action === 'first') {
                preBtn.hide();
            }
            wrap.show();
            var first = items[0];
            wrap.data('since_id', first.id);
            if (first.timestamp) {
                wrap.data('since_time', first.timestamp);
            }
            var last = items[items.length - 1];
            wrap.data('max_id', last.id);
            if (last.timestamp) {
                wrap.data('max_time', last.timestamp);
            }
        });
    }else{/*显示评论详细列表*/
        Weibo.Comments.show(params, function(err, data){
            loading.hide();
            if (err) {
                return ui.showErrorTips(err);
            }
            var nextBtn = wrap.find('.next_page');
            var preBtn = wrap.find('.pre_page');
            var items = data.comments;
            if (items.length === 0) {
                if (action === 'next') {
                    nextBtn.hide();
                } else if (action === 'prev') {
                    preBtn.hide();
                }
                return ui.showTips('没有了');
            }
            var html = '';
            var buildMethod = type === 'repost' ? 'buildRepost' : 'buildComment';
            for (var i = 0; i < items.length; i++) {
                html += ui[buildMethod](user, items[i]);
            }
            list.html(html);
            // set comment_#id data
            ViewCache.setCommentItems(items);
            if (buildMethod === 'buildRepost') {
                // cache them for repost
                ViewCache.setItems(items);
            }
            nextBtn.show();
            preBtn.show();
            if (action === 'first') {
                preBtn.hide();
            }
            wrap.show();
            var first = items[0];
            wrap.data('since_id', first.id);
            if (first.timestamp) {
                wrap.data('since_time', first.timestamp);
            }
            var last = items[items.length - 1];
            wrap.data('max_id', last.id);
            if (last.timestamp) {
                wrap.data('max_time', last.timestamp);
            }
        });
    }

};

MainController.prototype.gotop = function (event) {
    var tab = $('.tabs .active');
    var activeTimeline = tab.data('type');
    var warp = MainController.getWrap(activeTimeline);
    warp.scrollTop(0);
};

MainController.prototype.dialogcount = function (event) {
    var input = $(this);
    var parent = input.parent();
    var value = input.val();
    var max_length = parseInt(input.data('max_text_length'), 10) || 140;
    var len = max_length - (input.data('support_double_char') ? value.len() : value.length);
    // return [value, len, max_length];
    var sendBtn = parent.find('.send');
    var wlength = max_length - value.len();
    if (len === max_length) {
        sendBtn.attr('disabled', 'disabled');
    } else {
        sendBtn.removeAttr('disabled');
    }
    parent.find('.wordCount_double').html(wlength);
};

MainController.prototype.hideDialog = function (event) {
    var self = event.data.controller;
    $('#replyTextarea').blur();/*去掉焦点*/
    var dialog = $('#ye_dialog_window');
    dialog.hide();
    dialog.find('input[type="hidden"], input[type="checkbox"], textarea').val('');
    $('#upImgPreview_reply').hide().find('.img').html('');

    $('#chk_sendOneMore').hide();
    $('#txt_sendOneMore').hide();
    $('#chk_sendOneMore2').hide();
    $('#txt_sendOneMore2').hide();
};

MainController.prototype.sendReply = function (event) {
    sendMsgByActionType($('#replyTextarea').val().trim());
};

MainController.prototype.showRepostDialog = function (event) {
    var btn = $(this);
    var self = event.data.controller;

    var sid = btn.data('id');
    var status = ViewCache.get(sid) || ViewCache.getComment(sid);
    var screen_name = status.user.screen_name;
    var rtUserName;

    if (status.retweeted_status) {
        rtUserName = status.retweeted_status.user.screen_name || {};
    }

    $('#actionType').val('repost');
    $('#repostTweetId').val(status.id);
    $('#replyUserName').val(screen_name);

    $('#chk_sendOneMore').hide();
    $('#txt_sendOneMore').hide();
    $('#chk_sendOneMore2').hide();
    $('#txt_sendOneMore2').hide();

    $('#chk_sendOneMore').attr("checked", false).show();
    $('#txt_sendOneMore').text(i18n.get("msg_comment_too").format({username:screen_name})).show();
    if(rtUserName){
        $('#chk_sendOneMore2').attr("checked", false).val(sid).show();
        $('#txt_sendOneMore2').text(i18n.get("msg_comment_original_too")
            .format({username:rtUserName})).show();
    }

    $('#ye_dialog_title').html(i18n.get("msg_repost_who").format({username: screen_name}));
    $('#ye_dialog_window').show();
    var $t = $('#replyTextarea');
    var value = $t.val().trim();
    $t.focus().blur();
    if (!value) {
        if (status.retweeted_status) {
            var name = status.user.screen_name;
            value = '//' + '@' + name + ':' + status.text;
        } else {
            value = i18n.get("comm_repost_default");
        }
    }
    // 光标在前
    $t.val(value).focus();
    if (value === i18n.get("comm_repost_default")) {
        $t.select();
    }
    //_initText($t, config);
};
MainController.prototype.showCommentDialog = function (event) {
    var btn = $(this);
    var self = event.data.controller;

    var sid = btn.data('id');
    var status = ViewCache.get(sid) || ViewCache.getComment(sid);
    var rtUserName;

    if (status.retweeted_status) {
        rtUserName = status.retweeted_status.user.screen_name || {};
    }

    var uid = btn.data('uid');
    var screen_name = btn.data('screen_name');

    var cid = btn.data('cid') || '';
    var cuid = btn.data('cuid') || '';
    var comment_screen_name = btn.data('csn') || '';

    $('#actionType').val('comment');
    $('#commentTweetId').val(sid);
    $('#commentUserId').val(uid);

    $('#replyUserName').val(comment_screen_name);
    $('#replyUserId').val(cuid);
    $('#commentCommentId').val(cid);
    $('#ye_dialog_title').html(i18n.get("msg_comment_who").format({username: screen_name}));
    $('#ye_dialog_window').show();

    var value = $('#replyTextarea').removeAttr('disabled').val();
    var _txtRep = '';

    $('#chk_sendOneMore').attr("checked", false).val(sid).show();
    $('#txt_sendOneMore').text(i18n.get("msg_repost_too")).show();/*转发到我的微博*/

    if(rtUserName){
        $('#chk_sendOneMore2').attr("checked", false).val(sid).show();
        $('#txt_sendOneMore2').text(i18n.get("msg_comment_original_too")
            .format({username:rtUserName})).show();
    }

    var $replyText = $('#replyTextarea');
    $replyText.val('').focus().val(value).blur().val(value + _txtRep).focus();
};

MainController.prototype.getfriends_timeline = function (user, params, callback) {
    var loading = $('#loading').show();
    Weibo.Statuses.friends_timeline(params, function(err, data){
        loading.hide();
        if(err){
            return callback(err);
        }
        callback(err, data);

    });
};

MainController.prototype.Statuses_mentions = function (user, params, callback) {
    var loading = $('#loading').show();
    Weibo.Statuses.mentions(params, function(err, data){
        loading.hide();
        if(err){
            return callback(err);
        }
        callback(err, data);

    });
};
MainController.prototype.Comments_mentions = function (user, params, callback) {
    var loading = $('#loading').show();
    Weibo.Comments.mentions(params, function(err, data){
        loading.hide();
        if(err){
            return callback(err);
        }
        callback(err, data);

    });
};
MainController.prototype.Comments_timeline = function (user, params, callback) {
    var loading = $('#loading').show();
    Weibo.Comments.timeline(params, function(err, data){
        loading.hide();
        if(err){
            return callback(err);
        }
        callback(err, data);

    });
};
MainController.prototype.favorites = function (user, params, callback) {
    var loading = $('#loading').show();
    Weibo.Favorites.favorites(params, function(err, data){
        loading.hide();
        if(err){
            return callback(err);
        }
        callback(err, data);

    });
};

MainController.prototype.user_timeline = function (user, params, callback) {
    var loading = $('#loading').show();
    Weibo.Statuses.user_timeline(params, function(err, data){
        loading.hide();
        if(err){
            return callback(err);
        }
        callback(err, data);

    });
};
MainController.prototype.user_hot = function (user, params, callback) {
    var loading = $('#loading').show();
    Weibo.Suggestions.users_hot(params, function(err, data){
        loading.hide();
        if(err){
            return callback(err);
        }
        callback(err, data);

    });
};

MainController.prototype.show = function (event) {
    var self = event.data.controller;
    var clicktab = $(this);
    var tab = $('.tabs .active');
    tab.removeClass('active');
    clicktab.addClass('active');/*添加选种标示的类*/
    var activeTimeline = clicktab.data('type');/*获取点击的是哪一个按钮*/

    var warp = MainController.getWrap(activeTimeline);
    $('.list_p').hide();/*先把所有的列表隐藏*/
    warp.parent().show();
    if (clicktab.data('is_loading')){/*加载过程中，避免重复加载*/
        console.log("aaaaaaaaaaa" + clicktab.data('is_loading'));
        return;
    }
    var user = User.getUser();
    var params = {
        "source": Weibo.appKey.appKey,
        "access_token": user.access_token
    };
    self.showHeader(user);
    if(activeTimeline === 'friends_timeline'){/*首页*/

        clicktab.data('is_loading', true);
        /*获取微薄内容*/
        self.getfriends_timeline(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            self.showitem(user, data.statuses, activeTimeline, 'noappend');

        });

    }else if(activeTimeline === 'mentions'){/*@我*/
        clicktab.data('is_loading', true);
        /*获取微薄内容*/
        self.Statuses_mentions(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            self.showitem(user, data.statuses, activeTimeline, 'noappend');
        });

    }else if(activeTimeline === 'comments_mentions'){/*@评论*/
        clicktab.data('is_loading', true);
        /*获取微薄内容*/
        self.Comments_mentions(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            self.showitem(user, data.comments, activeTimeline, 'noappend');
        });

    }else if(activeTimeline === 'comments_timeline'){/*评论*/
        clicktab.data('is_loading', true);
        /*获取微薄内容*/
        self.Comments_timeline(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            self.showitem(user, data.comments, activeTimeline, 'noappend');
        });
    }else if(activeTimeline === 'favorites'){/*收藏*/
        var items = [];
        warp.data("page", 1);/*设置显示第一页*/
        clicktab.data('is_loading', true);
        /*获取微薄内容*/
        params.count = 20;
        self.favorites(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            for (var i = 0, len = data.favorites.length; i < len; i++) {
                items[i] = data.favorites[i].status;
            }
            self.showitem(user, items, activeTimeline, 'noappend');
        });
    }else if(activeTimeline === 'direct_messages_both'){/*私信*/


    }else if(activeTimeline === 'user_timeline'){/*我发送的微薄*/
        clicktab.data('is_loading', true);
        /*获取微薄内容*/
        self.user_timeline(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            self.showitem(user, data.statuses, activeTimeline, 'noappend');
            self.showMore($('.tabs .active'));
        });
    }else if(activeTimeline === 'user_hot'){/*热门微博*/
        var items = [];
        clicktab.data('is_loading', true);
        /*获取微薄内容*/
        self.user_hot(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            for (var i = 0, len = data.length; i < len; i++) {
                items[i] = data[i].status;
            }
            self.showitem(user, items, activeTimeline, 'noappend');
        });
    }else{
        console.log("not support this!");
        return;
    }


};

MainController.prototype.showMore = function (clicktab) {
    if (clicktab.data('is_loading')) {
        console.log("is_loading");
        return;
    }
    var self = this;
    var user = User.getUser();
    var activeTimeline = clicktab.data('type');
    var warp = MainController.getWrap(activeTimeline);
    var li = warp.find('ul li:last');
    var max_id = li.data('id');
    var timestamp = li.data('timestamp');

    var params = {
        "source": Weibo.appKey.appKey,
        "access_token": user.access_token
    };
    if (max_id) {
        params.max_id = max_id;
        if (timestamp) {
            params.max_time = timestamp;
        }
    }

    if(activeTimeline === 'friends_timeline'){/*首页*/
        clicktab.data('is_loading', true);
        self.getfriends_timeline(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            data.statuses.splice(0,1);/*删除数组胡第一个元素，防止显示重复的微薄*/
            if(data.statuses.length === 0){
                return ui.showTips('没有了');
            }
            self.showitem(user, data.statuses, activeTimeline, 'append');
        });
    }else if(activeTimeline === 'mentions'){/*@我*/

        clicktab.data('is_loading', true);
        self.Statuses_mentions(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            data.statuses.splice(0,1);/*删除数组胡第一个元素，防止显示重复的微薄*/
            if(data.statuses.length === 0){
                return ui.showTips('没有了');
            }
            self.showitem(user, data.statuses, activeTimeline, 'append');
        });

    }else if(activeTimeline === 'comments_mentions'){/*@评论*/
        clicktab.data('is_loading', true);
        self.Comments_mentions(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            data.comments.splice(0,1);/*删除数组胡第一个元素，防止显示重复的微薄*/
            if(data.comments.length === 0){
                return ui.showTips('没有了');
            }
            self.showitem(user, data.comments, activeTimeline, 'append');
        });
    }else if(activeTimeline === 'comments_timeline'){/*评论*/
        clicktab.data('is_loading', true);
        self.Comments_timeline(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            data.comments.splice(0,1);/*删除数组胡第一个元素，防止显示重复的微薄*/
            if(data.comments.length === 0){
                return ui.showTips('没有了');
            }
            self.showitem(user, data.comments, activeTimeline, 'append');
        });
    }else if(activeTimeline === 'favorites'){/*收藏*/
        var items = [];
        var page = warp.data("page") + 1;
        clicktab.data('is_loading', true);
        params.count = 20;
        params.page  = page;
        self.favorites(user, params, function(err, data) {
            clicktab.data('is_loading', false);
            if (err) {
                return ui.showErrorTips(err);
            }
            if(data.favorites.length === 0){
                return ui.showTips('没有了');
            }
            warp.data("page", page);/*设置页码*/
            //data.favorites.splice(0, 1);
            for (var i = 0, len = data.favorites.length; i < len; i++) {
                items[i] = data.favorites[i].status;
            }
            /*删除数组胡第一个元素，防止显示重复的微薄*/
            self.showitem(user, items, activeTimeline, 'append');
        });
    }else if(activeTimeline === 'direct_messages_both'){/*私信*/
    }else if(activeTimeline === 'user_timeline'){/*我发送的微薄*/
        clicktab.data('is_loading', true);
        self.user_timeline(user, params, function(err, data){
            clicktab.data('is_loading', false);
            if(err){
                return ui.showErrorTips(err);
            }
            data.statuses.splice(0,1);/*删除数组胡第一个元素，防止显示重复的微薄*/
            if(data.statuses.length === 0){
                return ui.showTips('没有了');
            }
            self.showitem(user, data.statuses, activeTimeline, 'append');
        });
    }else{
        console.log("not support this!");
        return;
    }
};

MainController.prototype.showitem = function (user, items, timeline, append) {
    if (!items || !items.length) {
        return;
    }
    var _ul = $("#" + timeline + "_timeline ul.list");
    var htmls = ui.buildStatusHtml(items, timeline, user);
    if(append === 'append'){
        /*滚动*/
        _ul.append(htmls.join(''));
    }else if ( append === 'noappend'){
        /*整个页面刷新*/
        _ul.html(htmls.join(''));
    }

    ViewCache.setItems(items);/*需要放在_ul.append后面，确保'#tweet' + item.id'已经更新完成*/

};

MainController.getWrap = function (timeline) {
    return $('#' + timeline + '_timeline .list_warp');
};

MainController.prototype.checkScroll = function (event) {
    var self = event.data.controller;
    var tab = $('.tabs .active');
    var activeTimeline = tab.data('type');
    var wrap = MainController.getWrap(activeTimeline);
    var btn = $('#gototop');
    var scrollTop = wrap.scrollTop();
    if (scrollTop > 130) {
        btn.show();
    } else {
        btn.hide();
    }
    if (scrollTop > 0) {
        var scrollHeight = wrap.prop('scrollHeight') - wrap.height();
        if (scrollTop >= scrollHeight) {
            console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaccccccccccccccccccccc");
            /*显示下一页*/
            self.showMore(tab);
        }
    }
};
MainController.prototype.showHeader_top = function (user) {
    var header = $("#header .user");
    header.find('.face, .name_link').attr('rhref', user.t_url).data('uid', user.id);
    header.find('.face .icon').attr('src', user.profile_image_url);
    //header.find('.face .bt').attr('src', 'images/blogs/' + user.blogType + '_16.png');
    header.find('.info .name').html(user.screen_name);
    var nums = '';
    nums += user.name + '&nbsp;&nbsp;&nbsp;&nbsp;';
    nums += format(i18n.get("comm_counts_info"), user);
    if (user.favourites_count !== undefined) {
        nums += ', ' + user.favourites_count + i18n.get("comm_favourite");
    }
    header.find('.info .nums').html(nums);
};

MainController.prototype.showHeader = function (user) {
    var header = $("#userinfo");
    var info = user.screen_name + '\r\n' + '关注' + '：' + user.friends_count + '\r\n' +
        '粉丝' + '：' + user.followers_count + '\r\n' +
        '微博' + '：' + user.statuses_count + '';

    header.find('.info-detail .icon').attr('src', user.profile_image_url);
    header.find('.info-detail').attr('title', info);
    header.click();

};

function URLController() {
    this.events = [
        { events: 'click', selecter: 'a', handler: this.openLink },
        {
            events: 'click',
            selecter: '.status_text_link, .status_text_link_expand, .status_hash_link',
            handler: this.openStatusLink
        },
        { events: 'mousedown', selecter: 'a', handler: this.openRealLink}
    ];

    URLController.super_.call(this);

}

inherits(URLController, Controller);

URLController.prototype.openRealLink = function (event) {
    if (event.which === 3) {
        var alink = $(this);
        var url = alink.data('rhref') || alink.attr('rhref') || alink.attr('href');
        url && openOnBrowser(url);
        return false;
    }
};

URLController.prototype.openLink = function (event) {
    var alink = $(this);
    var url = alink.data('href');
    if (url && url.indexOf('http') === 0) {
        openOnBrowser(url);
        return false;
    }
};

URLController.prototype.openStatusLink = function (event) {
    var alink = $(this);
    var url = alink.attr('href');
    if (url && url.indexOf('http') === 0) {
        openOnBrowser(url);
        return false;
    }
};
function FavoriteController() {
    this.events = [
        { events: 'click', selecter: '.add_favorite_btn', handler: this.add },
        { events: 'click', selecter: '.del_favorite_btn', handler: this.del },
    ];
/*
    $('.add_favorite_btn').removeClass();
    $('.add_favorite_btn').addClass();
*/

    FavoriteController.super_.call(this);
}

inherits(FavoriteController, Controller);

FavoriteController.prototype.add = function (event) {
    var controller = event.data.controller;
    var btn = $(this);
    btn.hide();
    var id = btn.data('id');
    var user = User.getUser();
    var para = {
        "source": Weibo.appKey.appKey,
        "access_token": Weibo.appKey.access_token,
        "id"          : id
    };
    Weibo.Favorites.create(para, function (err, result) {
        if (err) {
            console.error(err);
            ui.showErrorTips(err);
            btn.show();
            return;
        }
        btn.find('img').attr('src', 'images/favorites.gif');
        btn.removeClass('add_favorite_btn').addClass('del_favorite_btn').show();
        // TODO cache the favorite items
        ui.showTips(i18n.get("msg_add_favorites_success"));
    });
};

FavoriteController.prototype.del = function (event) {
    var self = event.data.controller;
    var btn = $(this);
    btn.hide();
    var id = btn.data('id');
    var user = User.getUser();
    var para = {
        "source": Weibo.appKey.appKey,
        "access_token": Weibo.appKey.access_token,
        "id"          : id
    };
    Weibo.Favorites.destroy(para, function (err, result) {
        if (err) {
            console.error(err);
            ui.showErrorTips(err);
            btn.show();
            return;
        }
        btn.find('img').attr('src', 'images/favorites_2.gif');
        btn.removeClass('del_favorite_btn').addClass('add_favorite_btn').show();
        ui.showTips(i18n.get("msg_del_favorites_success"));
    });
}

var ViewCache = {
    setItems: function (items) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var id = '#tweet' + item.id;
            $(id).data('originalItem', item);
            if (item.retweeted_status) {
                id = '#tweet' + item.retweeted_status.id;
                $(id).data('originalItem', item.retweeted_status);
                if (item.retweeted_status.retweeted_status) {
                    id = '#tweet' + item.retweeted_status.retweeted_status.id;
                    $(id).data('originalItem', item.retweeted_status.retweeted_status);
                }
            }
        }
    },
    setCommentItems: function (items) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var id = '#comment_' + item.id;
            $(id).data('originalItem', item);
        }
    },
    get: function (id) {
        return $('#tweet' + id).data('originalItem');
    },
    getComment: function (cid) {
        return $('#comment_' + cid).data('originalItem') || this.get(cid);
    }
};

function oauth_callback(url) {

    var urlinfo = urlparse(url, true);
    var query = urlinfo.query || {};
    var pin = query.oauth_verifier || query.code || 'impin';
    var tdata = [];
    if (pin.indexOf('#') > 0) {
        pin = pin.substring(0, pin.indexOf('#'));
    }
    console.log(pin);

     var jsonParas = {
         code:pin,
         grant_type:"authorization_code"
     };
    console.log("222222222222");
    Weibo.OAuth2.access_token(jsonParas,function(err, data){
         console.log(data);

              // set parameters
         Weibo.appKey.access_token = data.access_token;
         /*获取到access_token*/
         var para = {
             "source": Weibo.appKey.appKey,
             "access_token": Weibo.appKey.access_token
         };
        tdata = data;

        var para = {
            "source": Weibo.appKey.appKey,
            "access_token": Weibo.appKey.access_token,
            "uid":tdata.uid
        };
        console.log("3333333333333");
        // get public timeline
        Weibo.Users.show(para, function(err, data){
            console.log(data);
            $.extend(data, tdata);/*添加 access_token uid等信息*/
            User.saveUser(data);
            window.open("./index.html", '_blank');

        });
/*
         console.log("3333333333333");
         // get public timeline
         Weibo.Statuses.friends_timeline(para, function(err, data){
             items=data.Array;
             console.log(data);

         });
*/

     });

}


function f_login() {
    // 跳到登录页面
        var callbackURL = Weibo.appKey.redirectUrl;
        var oauth_URL = 'https://api.t.sina.com.cn/oauth2/authorize?client_id=' + Weibo.appKey.appKey + '&redirect_uri=' + Weibo.appKey.redirectUrl
            + '&response_type=code';
        setTimeout(function () {
            console.log("3434343434aaaaaaaaaaaaaaaaaaaa");

            var win = window.open(oauth_URL, '_blank');
            $(win).on('load', function () {
                console.log('load: ' + win.location.href);
                var timer = setInterval(function () {
                    var url = win.location.href;
                    if (url.indexOf(callbackURL+"?code") < 0) {
                        return;
                    }
                    clearInterval(timer);
                    win.close();
                    win = null;
                    oauth_callback(url);

                }, 500);
            });
        }, 1000);
}
function resizeWindow(w, h) {
    if (!w) {
        w = window.innerWidth;
    }
    if (!h) {
        h = window.innerHeight;
    }

    var wh_css = '#wrapper{width:'+ w +'px;}' +
        '#txtContent{width:'+ (w - 2) +'px;}' +
        '.warp{width:' + w + 'px;}' +
        '#pb_map_canvas, #popup_box .image img, #popup_box .image canvas{max-width:'+ (w - 20) +'px;}';
    $("#styleCustomResize").html(wh_css);

    var nav_sho = $("#nav_pro_selid");
    var showData = nav_sho.data('show');
    var wrapper = $('#wrapper');
    var warp = $('.warp');
    var submitWarp = $('#submitWarp');
/*
    console.log('wrapper:'+wrapper.height());
    console.log('warp:'+warp.height());
    console.log('submitWarp:'+submitWarp.height());
*/
    showData = nav_sho.data('show');
    $('.tab-friends_timeline').click();

    if(showData === 'hide') {
        wrapper.width(window.innerWidth-81);
        /**/
        warp.width(window.innerWidth-81);
    }else if(showData === 'shown'){
        wrapper.width(window.innerWidth-131);
        /**/
        warp.width(window.innerWidth-131);
    }
    /*防止右边栏出现滚动条*/
    var $submitWarp = $('#submitWarp');
    if ($submitWarp.data('status') !== 'show') {
        var h = window.innerHeight-2;/!*防止右边栏出现滚动条*!/
        $(".list_warp").height(h);
    }else{
        var h_submitWrap = $submitWarp.find(".w").height();
        var h = window.innerHeight - h_submitWrap;
        $('.list_warp').height(h);
    }
};

function IndexController(){
    var nav_sho = $("#nav_pro_selid");
    var showData = nav_sho.data('show');
    var wrapper = $('#wrapper');
    var warp = $('.warp');
    var wWidth;
    var windowWidth;
    this.events = [];

    $("#nav_left_hideid").click(function(){
        nav_sho.slideToggle();
        windowWidth = $(window).width();
        wWidth = wrapper.width();
        showData = nav_sho.data('show');
        //to show
        if(showData == 'hide')
        {
            setTimeout(function () {
                wrapper.css({
                    left: "66px"
                });
                wrapper.width(windowWidth-131);
                /**/
                warp.width(windowWidth-131);
                nav_sho.data('show', 'shown');
                $('#nav_left_hideid').removeClass('glyphicon glyphicon-menu-right').addClass('glyphicon glyphicon-menu-left').css({
                    left: '56px'
                });
            },0);
        }else if(showData == 'shown'){
            setTimeout(function () {
                wrapper.css({
                    left: "16px"
                });
                wrapper.width(windowWidth-81);
                /**/
                warp.width(windowWidth-81);

                console.log('wWidth='+wWidth);
                nav_sho.data('show', 'hide');

                $('#nav_left_hideid').removeClass('glyphicon glyphicon-menu-left').addClass('glyphicon glyphicon-menu-right').css({
                    left: '0px'
                });
            },500);
        }
    });
    IndexController.super_.call(this);
    //setInterval(function(){
    //    windowWidth = $(window).width();
    //    wWidth = wrapper.width();
    //    //wWidth = $('#wrapper').width();
    //    if((windowWidth > wWidth+131) || (windowWidth < wWidth+81)){
    //        //console.log("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb:windowWidth-"+windowWidth+"wWidth+131--"+wWidth+131+"wWidth+81--"+wWidth+81);
    //        showData = nav_sho.data('show');
    //        if(showData == 'hide') {
    //            //alert("showData："+showData);
    //            wrapper.width(windowWidth-81);
    //        }else if(showData == 'shown'){
    //            //alert("showData："+showData);
    //            wrapper.width(windowWidth-131);
    //        }
    //    }
    //    //console.log('windowWidth:'+windowWidth+'wWidth:'+wWidth);
    //},500);
}
inherits(IndexController, Controller);

function TextController(){
    this.$textContent = $('#txtContent');
    var btn = $('#btnSend');

    this.events = [
        { events: 'click', selecter: '#show_status_input', handler: this.toggleTextInput }
        //{ events: 'click', selecter: '#btnClearText', handler: this.clearText}
    ];
    this.$textContent.on('input focus', { controller: this }, this.count);
    btn.click(this.send.bind(this));
    //$('#btnClearText').click(this.clearText);
    $('#btnClearText').click(this.clearText.bind(this));

    TextController.super_.call(this);
}
inherits(TextController, Controller);

TextController.prototype.clearText = function(event){
    //console.log('clearText clearText clearText'+this.val());
    //var input = $(this);
    //input.val('111111111111111');
    this.$textContent.val('').focus();
    //this.$textContent.val('').focus();
};
TextController.prototype.count= function (event) {
    var input = $(this);
    var parent = input.parent();
    var value = input.val();
    var max_length = 140;
    var sendBtn = parent.find('.send');
    var conut_ch = $('.wordCount_double');
    var conut_pa = $('.wordCount');
    var freecount = max_length -value.length;

    conut_ch.html(value.length);
    conut_pa.html(freecount);
    if(value.length >= max_length)
    {
        input.attr('disabled', 'disabled');
    }else{
        input.removeAttr('disabled');
    }
    //console.log('value.lenght:'+value.length);
    if(value.length <= 0)
    {
        console.log('value.lenght:'+value.length);
        sendBtn.attr('disabled', 'disabled');
    }else{
        sendBtn.removeAttr('disabled');
    }
    //var max_length = parseInt(input.data('max_text_length'), 10) || 140;
};
TextController.prototype.send = function(){
    console.log('TextController.prototype.send');
    var text = this.$textContent.val().trim();
    //todo
    //if (!text) {
    //    showMsg(i18n.get("msg_need_content"));
    //}
    console.log('text:'+text);  //0 great
    sendMsg(text);
};
function sendMsg(msg){
    console.log('sendMsg coming');
    var btn = $("#btnSend"),
        txt = $("#txtContent");
    var visible = 0;//默认所有人可见
    var user = User.getUser();

    //Now disable the txt & btn
    btn.attr('disabled','true');
    txt.attr('disabled','true');
    var selectval = $(".selectpicker option:selected").val();

    if(selectval === '自己可见'){
        visible = 1;
    }else if(selectval === '朋友圈可见'){
        visible = 2;
    }else{//公开可见
        visible = 0;
    }
    var para = {
        "source": Weibo.appKey.appKey,
        "access_token": user.access_token,
        "status": msg,
        "visible":visible
    };
    Weibo.Statuses.update(para, function (err, data) {
        console.log(data);  //0
        console.log(err);  //0
    });
    $("#btnSend, #txtContent").removeAttr('disabled');
    $('#show_status_input').click();
}
TextController.prototype.toggleTextInput = function(event){
    //console.log('toggleTextInput coming');    //1
    var self = event.data.controller;
    var preview = $("#upImgPreview");
    if ($("#submitWarp").data('status') !== 'show') {
        //console.log('toggleTextInput if coming');  //1
        self.showTextInput();
        if (window.imgForUpload) {
            setTimeout(function () {
                preview.show();
            }, 500);
        }
        return;
    }
    console.log('toggleTextInput coming end');  //1
    preview.hide();
    self.hideTextInput();
};
TextController.prototype.showTextInput = function(event){
    //console.log('showTextInput coming');
    var $submitWarp = $('#submitWarp');
    if ($submitWarp.data('status') !== 'show') {
        console.log('showTextInput if coming');//1
        //initSelectSendAccounts();
        var h_submitWrap = $submitWarp.find(".w").height();
        var h = window.innerHeight - h_submitWrap;
        console.log('h_submitWrap:'+h_submitWrap);
        console.log('window.innerHeight:'+window.innerHeight);
        console.log('h:'+h);
        $('.list_warp').css('height', h);
        $submitWarp.data('status', 'show').css('height', h_submitWrap);
        //$('#doing').appendTo('#doingWarp');
        // ActionCache.set('showMsgInput', []);

        //var btn = $("#btnSend");
        //btn.attr('disabled','true');
        var txt = $('#txtContent');

        /*
                txt.val('xxxxxxxxxxxxxxxx');//ok
                var tmp = txt.val();
                var tmp = tmp + '11111';
                console.log('wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww'+tmp);//not work
                txt.val(tmp);//ok
        */

        /**/
        if(txt.lenght)
        {
            $("#btnSend").removeAttr('disabled');
        }else{
            $("#btnSend").attr('disabled', 'true');
        }

    }
    //var value = this.$textContent.val();
    //this.$textContent.focus().val('').val(value); //光标在最后面
};
TextController.prototype.hideTextInput = function(){

    $('#btnFaceBoxClose').click();
    console.log('window.innerHeight:'+window.innerHeight);
    var h = window.innerHeight-2;/*防止右边栏出现滚动条*/
    $(".list_warp").css('height', h);
    $("#submitWarp").data('status', 'hide').css('height', 0);
    this.$textContent.blur(); // 让它失去焦点，避免快捷键被输入了
};

function EmotionController() {
    this.events = [
        { events: 'click', selecter: '#face_box .face_item', handler: this.insert },
        { events: 'click', selecter: '#btnAddEmotional, #btnAddReplyEmotional', handler: this.show },
        { events: 'click', selecter: '#btnFaceBoxClose', handler: this.hide },
    ];
    EmotionController.super_.call(this);
}
inherits(EmotionController, Controller);
/* 表情添加到textarea */
EmotionController.prototype.insert = function (event) {
    var self = event.data.controller;
    var btn = $(this);
    //alert('face_box_target_id\'s value:'+$("#face_box_target_id"));
    var $target_textbox = $("#" + $("#face_box_target_id").val());
    if ($target_textbox.length === 1) {
        var tb = $target_textbox[0];
        var str = btn.attr('value');
        var newstart = tb.selectionStart + str.length;
        tb.value = tb.value.substr(0, tb.selectionStart) + str + tb.value.substring(tb.selectionEnd);
        tb.selectionStart = newstart;
        tb.selectionEnd = newstart;
    }
    self.hide();
};
/* btn_emotinal's handler */
EmotionController.prototype.show = function (event) {
    //console.log('EmotionController show');
    var self = event.data.controller;
    var btn = $(this);
    var target_id = btn.data('target');//txtContent
    var f = $("#face_box");

    /* just for test */
    if(!target_id === 'txtContent')
        //alert('target_id:'+target_id);

    if (!f.is(':hidden') && $("#face_box_target_id").val() === target_id) {
        f.hide();
        return;
    }
    // 初始化表情
    if ($('#face_box .faceItemPicbg .face_icons').length === 0) {
        self.initBox();
    }
    $("#face_box_target_id").val(target_id);    /* 为上一个if判断 */
    var offset = btn.offset();
    var left = offset.left - 100;	 /* face_box位置调整 */
    var arrow_left = 50;//0
    //if ($('#replyTextarea').length > 0 && !$('#replyTextarea').is(':hidden')) {
    //    left = $('#ye_dialog_window').position().left;
    //    arrow_left = 120;
    //}
    f.css({top: offset.top + 35, left: left}).show();
    f.find('.layerArrow').css({left: arrow_left});
};

EmotionController.prototype.hide = function () {
    $("#face_box").hide();
    $("#face_box_target_id").val('');
};
/* face_box的填充 */
EmotionController.prototype.initBox = function () {
    // FACE_TYPES  key: [faces, url_pre, tpl, type_title]
    //console.log('init coming'+FACE_TYPES);
    var done = 0;
    for (var k in FACE_TYPES) {
        //face_type: tecent taobao and so on
        //face_tab: tecent taobao and so on
        var face_type = FACE_TYPES[k];
        //alert('face_type:'+face_type[3]);
        //var $face_tab = '';
        var $face_tab = $('<span face_type="' + k + '">' + face_type[3] + '</span>');
        /* 对每个都做了一个click事件的绑定 */
        $face_tab.click(function () {
            //console.log('$face_tab 00000000000000000000000'+$face_tab);
            //sina tecent 各个块的选择
            var $this = $(this);
            if (!$this.hasClass('active')) {
                //console.log('not has active');
                $('.face_tab span').removeClass('active');  /* remove all of the spans's class of active */
                $('#face_box .faceItemPicbg .face_icons').hide();   /* remove all of the face_icons' class of show */
                $('#face_box .faceItemPicbg .' + $this.attr('face_type') + '_faces').show();    /* show only */
                $this.addClass('active');   /* active only */
            }
        });

        if(done) continue;  /* 解决sina表情重复问题 */
        if(face_type[3] !== '新浪') continue; /* 屏蔽sina以外的表情 */

        done = 1;
        var $face_icons = $('<div style="display:none;" class="face_icons ' + k + '_faces"></div>');    /* generate $face_icons */
        $('#face_box .face_tab p').append($face_tab); /* 只有sina表情，故无需再添加tab标识 */
        $('#face_box .faceItemPicbg').append($face_icons);
        var exists = {};

        $('#face_icons li a').each(function() {
            console.log('hhhhhhhhhhhhhhhhhhhhhhhhhhhhh' + $(this).attr('title'));
            exists[$(this).attr('title')] = true;

        });
        var face_tpl = face_type[2];
        console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxx'+face_tpl[0]);//[{{name}}] [
        var faces = face_type[0];
        if (face_tpl) {
            /* 模板 */
            var tpl = '<li><a href="javascript:;" class="face_item" value="' + face_tpl +
                '" title="{{name}}"><img src="{{url}}" alt="{{name}}"></a></li>';
            var url_pre = face_type[1];
            for (var name in faces) {
                console.log('name='+name);  /* 表情name打印 */
                if (exists[name]) {
                    continue;
                }
                $face_icons.append(tpl.format({'name': name, 'url': url_pre + faces[name]}));
                exists[name] = true;
            }
        } else {
            console.log('else else');
            var tpl = '<li class="tsina"><a href="javascript:;" class="face_item" value="{{name}}" title="{{title}}">{{name}}</a></li>'; //yanwenzi
            for (var name in faces) {
                $face_icons.append(tpl.format({'name': name, 'title': faces[name]}));
            }
        }
    }
    var blogtype = User.getUser().blogtype;
    console.log('blogtype:'+blogtype);
    var $selected = $("#accountsForSend li.sel");
    if ($selected.length > 1) {
        blogtype = 'tsina';
    } else if ($selected.length === 1) {
        blogtype = $selected.attr('blogType');
    }
    var $face_type_tab = $('#face_box .face_tab span[face_type="' + blogtype + '"]');
    if ($face_type_tab.length === 0) {
        $face_type_tab = $('#face_box .face_tab span[face_type="tsina"]');
    }
    /* 激活，否则需要手动点击激活 */
    $face_type_tab.click();
};
function do_login() {
    console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    resizeWindow();
    $(window).resize(resizeWindow);
    new URLController();/*URL超级链接控制器*/
    new StatusController();/*图片放大缩小控制器*/
    new MainController();/*图片放大缩小控制器*/
    new IndexController();      /* 布局控制器 */
    new TextController();       /* 微博发布控制器 */
    new EmotionController();    /* 表情添加控制器 */
    new FavoriteController();
    Weibo.init(setting);
    var user = User.getUser();

    //判断是否有cookie
    if(user){
        /* 页面初始化*/
        //weibo_init();

    }else{//跳转到登录页面进行授权
        f_login();
    }
    //$(document).ready(function(){
    //    $('.tab-friends_timeline').click();
    //});
    /* 需要2s延迟 */
    setTimeout(function(){
        $('.tab-friends_timeline').click();
    },2000);
}

function weibo_init()
{
    /*初始化各种各样的监听控制器*/
    //new TextContentController();
    var user = User.getUser();
    var _url = [];

    console.log("3333333333333");
    var para = {
        "source": Weibo.appKey.appKey,
        "access_token": user.access_token
    };

    Weibo.Statuses.friends_timeline(para, function(err, data){
        //var items=data.Array;
        console.log(data);
        var htmls = ui.buildStatusHtml(data.statuses,user);

        _ul = $("#friends_timeline_timeline ul.list");

        _ul.append(htmls.join(''));

    });



}

function openNewWindow(url, specs) {
    if (url) {
        url = url.trim();
    }
    if (!url || url.indexOf('javascript') === 0) {
        return false;
    }
    specs = specs || {};
    if (!specs.width) {
        specs.width = window.screen.width * 0.9;
    }
    if (!specs.height) {
        specs.height = window.screen.height;
    }
    var s = [];
    for (var k in specs) {
        s.push(k + '=' + specs[k]);
    }
    window.open(url, '_blank', s.join(','));
    return false;
}

function openOnBrowser(url) {
    shell.open(url);
}
/*这种写法相当于html加载完成后在执行*/
$(function () {
    do_login();
});

function format(s, values) {
    var STRING_FORMAT_REGEX  = /\{\{([\w\s\.\'\"\(\),-\[\]]+)?\}\}/g;
    var cb;
    if (typeof values === 'function') {
        cb = values;
    } else {
        cb = function (match, key) {
            try {
                return values[key] || eval('(values.' + key + ')');
            } catch (e) {
                console.log(JSON.stringify([s, values, key]));
                // return s;
                throw e;
            }
        };
    }
    return s.replace(STRING_FORMAT_REGEX, cb);
}
